import time
from ely.poundmonitor.stats import Stats
from pprint import pprint
import math

OFFSET = 60*20


class ParseError(Exception):
    """Error parsing a syslog line.
    """


def date(parts):
    year = time.localtime()[0]
    date = ' '.join([str(year)]+parts[:3])
    date = time.mktime(time.strptime(date, '%Y %b %d %H:%M:%S'))
    offset = time.time() - date
#     if offset < 0:
#         raise ParseError('Log entry is from the future.', parts)
#     if offset > OFFSET:
#         raise ParseError('Log entry is too old.', parts, offset)
    return date


def parse(line):
    parts = line.split()
    if len(parts) < 5:
        return
    if parts[4] != 'pound:':
        return
    if parts[-1] != 'sec':
        return
    if parts[-4] != '->':
        return
    backend = parts[-3]
    if backend[-1] != ')':
        return
    backend = backend[:-1]
    delay = float(parts[-2])
    return date(parts), backend, delay


def parse_log(log, backend, interval=300):
    stats = Stats()
    threshold = None
    for line in log:
        try:
            result = parse(line)
        except ParseError:
            result = None
        if result is not None:
            date, _, _ = result
            stats.record(*result)
            if threshold is None:
                threshold = date
            if date > threshold:
                threshold += interval
                display(stats, backend)
                stats = Stats()


def display(stats, backend):
    response_times = stats.calculate()
    response_times = response_times.setdefault(backend, (0,0,0,0))
    print '%s: %.3f\t %.3f\t %.3f\t %.3f\t' % (
        (time.ctime(stats.last_date),) +
        response_times)


def monitor(stream, stats):
    for line in stream:
        result = parse(line)
        if result is not None:
            stats.record(*result)
